package com.google.code.b0rx0r.program;

import java.util.ArrayList;
import java.util.List;

import com.google.code.b0rx0r.TempoProvider;

public class ProgramManager {
	private List<Program> programs = new ArrayList<Program>();
	private TempoProvider tempoProvider;
	
	private int currentProgramIndex;
	private Program currentProgram;
	
	private List<ProgramManagerListener> listeners = new ArrayList<ProgramManagerListener>();

	public ProgramManager(TempoProvider tempoProvider) {
		this.tempoProvider = tempoProvider;
		Program p = new Program(this);
		programs.add(p);
		setCurrentProgramIndex(0);
	}
	

	public void setCurrentProgramIndex(int currentProgramIndex) {
		this.currentProgramIndex = currentProgramIndex;
		setProgram(programs.get(currentProgramIndex));
	}
	
	public Program getProgram() {
		return currentProgram;
	}

	public void setProgram(Program program) {
		program.setProgramManager(this);
		
		Program oldProgram = getProgram();
		this.currentProgram = program;
		programs.set(currentProgramIndex, program);
		
		if (oldProgram != program)
			fireProgramChanged(oldProgram, program);
		
	}
	
	private void fireProgramChanged(Program old, Program newProgram) {
		for (ProgramManagerListener listener : listeners) {
			listener.programChanged(old, newProgram);
		}
	}

	public void addProgramManagerListener(ProgramManagerListener listener) {
		listeners.add(listener);
	}
	
	public void removeProgramManagerListener(ProgramManagerListener listener) {
		listeners.remove(listener);
	}

	public int getProgramCount() {
		return programs.size();
	}

	public int getCurrentProgramIndex() {
		return currentProgramIndex;
	}


	public Program getProgram(int index) {
		return programs.get(index);
	}


	public TempoProvider getTempoProvider() {
		return tempoProvider;
	}

	

}
